using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using MediPlatform.Domain.Order;
using MediPlatform.Read.Api.Models;
using MediPlatform.Infeartructure;

namespace MediPlatform.Read.Api.Services
{
    /// <summary>
    /// 退款申请服务
    /// </summary>
    public class RefundApplicationService
    {
        private readonly MyDbContext _context;
        private readonly ILogger<RefundApplicationService> _logger;

        public RefundApplicationService(MyDbContext context, ILogger<RefundApplicationService> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取退款申请分页列表
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>分页结果</returns>
        public async Task<RefundApplicationPagedResponse> GetPagedListAsync(RefundApplicationQueryRequest request)
        {
            _logger.LogInformation("开始查询退款申请列表，参数: {@Request}", request);

            var query = _context.RefundApplication
                .Include(x => x.User) // 包含用户信息
                .AsQueryable();

            // 应用筛选条件
            query = ApplyFilters(query, request);

            // 获取总数
            var totalCount = await query.CountAsync();
            _logger.LogInformation("筛选后总记录数: {TotalCount}", totalCount);

            // 计算分页
            var totalPages = totalCount > 0 ? (int)Math.Ceiling((double)totalCount / request.PageSize) : 0;
            var skip = (request.PageIndex - 1) * request.PageSize;

            _logger.LogInformation("分页信息: 总记录数={TotalCount}, 总页数={TotalPages}, 跳过={Skip}, 获取={Take}", totalCount, totalPages, skip, request.PageSize);

            // 获取分页数据
            var items = await query
                .OrderByDescending(x => x.ApplyTime)
                .Skip(skip)
                .Take(request.PageSize)
                .Select(x => new RefundApplicationListItem
                {
                    Id = x.Id,
                    ApplicationNo = x.ApplicationNo,
                    ApplyTime = x.ApplyTime,
                    UserPhone = x.User != null ? x.User.PhoneNumber : "13800138001", // 临时使用固定手机号
                    Amount = x.Amount,
                    Source = GetSourceText(x.RefundType, x.ExtraInfo),
                    Status = x.Status,
                    StatusText = GetStatusText(x.Status),
                    ProcessTime = x.ProcessTime
                })
                .ToListAsync();

            _logger.LogInformation("查询到 {ItemCount} 条记录", items.Count);

            var result = new RefundApplicationPagedResponse
            {
                Items = items,
                TotalCount = totalCount,
                TotalPages = totalPages,
                CurrentPage = request.PageIndex,
                PageSize = request.PageSize
            };

            return result;
        }

        /// <summary>
        /// 获取退款申请详情
        /// </summary>
        /// <param name="id">申请ID</param>
        /// <returns>详情信息</returns>
        public async Task<RefundApplicationDetailResponse?> GetDetailAsync(long id)
        {
            var application = await _context.RefundApplication
                .FirstOrDefaultAsync(x => x.Id == id);

            if (application == null)
                return null;

            // 获取退款日志
            var refundLogs = await _context.RefundLog
                .Where(x => x.ApplicationId == id)
                .OrderByDescending(x => x.OperateTime)
                .Select(x => new RefundLogItem
                {
                    Id = x.Id,
                    Status = x.Status,
                    StatusText = GetStatusText(x.Status),
                    OperatorId = x.OperatorId,
                    OperateTime = x.OperateTime,
                    Remark = x.Remark
                })
                .ToListAsync();

            var result = new RefundApplicationDetailResponse
            {
                Id = application.Id,
                ApplicationNo = application.ApplicationNo,
                OrderId = application.OrderId,
                UserId = application.UserId,
                Amount = application.Amount,
                Status = application.Status,
                StatusText = GetStatusText(application.Status),
                ApplyTime = application.ApplyTime,
                ProcessTime = application.ProcessTime,
                ProcessorId = application.ProcessorId,
                Remark = application.Remark,
                RefundChannel = application.RefundChannel,
                RefundType = application.RefundType,
                ExtraInfo = application.ExtraInfo,
                RefundLogs = refundLogs
            };

            return result;
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns>总数</returns>
        public async Task<int> GetTotalCountAsync()
        {
            var count = await _context.RefundApplication.CountAsync();
            return count;
        }

        /// <summary>
        /// 根据状态获取数量
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns>数量</returns>
        public async Task<int> GetCountByStatusAsync(int status)
        {
            var count = await _context.RefundApplication.CountAsync(x => x.Status == status);
            return count;
        }

        /// <summary>
        /// 确认退款申请
        /// </summary>
        /// <param name="request">确认退款请求</param>
        /// <returns>处理结果</returns>
        public async Task<bool> ConfirmRefundAsync(ConfirmRefundRequest request)
        {
            try
            {
                _logger.LogInformation("开始确认退款申请，ID：{Id}", request.Id);

                // 获取退款申请
                var application = await _context.RefundApplication
                    .FirstOrDefaultAsync(x => x.Id == request.Id);

                if (application == null)
                {
                    _logger.LogWarning("退款申请不存在，ID：{Id}", request.Id);
                    return false;
                }

                // 检查状态是否为待处理
                if (application.Status != 0)
                {
                    _logger.LogWarning("退款申请状态不是待处理，无法确认，ID：{Id}，当前状态：{Status}", request.Id, application.Status);
                    return false;
                }

                // 更新退款申请状态
                application.Status = 1; // 已处理
                application.ProcessTime = DateTime.Now;
                application.ProcessorId = request.OperatorId;
                application.Remark = request.Remark;
                application.UpdatedAt = DateTime.Now;

                // 创建退款日志
                var refundLog = new RefundLog
                {
                    ApplicationId = request.Id,
                    Status = 1, // 已处理
                    OperatorId = request.OperatorId,
                    OperateTime = DateTime.Now,
                    Remark = request.Remark ?? "确认退款",
                    CreatedAt = DateTime.Now
                };

                // 保存到数据库
                _context.RefundLog.Add(refundLog);
                await _context.SaveChangesAsync();

                _logger.LogInformation("退款申请确认成功，ID：{Id}", request.Id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "确认退款申请失败，ID：{Id}", request.Id);
                return false;
            }
        }

        /// <summary>
        /// 拒绝退款申请
        /// </summary>
        /// <param name="request">拒绝退款请求</param>
        /// <returns>处理结果</returns>
        public async Task<bool> RejectRefundAsync(RejectRefundRequest request)
        {
            try
            {
                _logger.LogInformation("开始拒绝退款申请，ID：{Id}", request.Id);

                // 获取退款申请
                var application = await _context.RefundApplication
                    .FirstOrDefaultAsync(x => x.Id == request.Id);

                if (application == null)
                {
                    _logger.LogWarning("退款申请不存在，ID：{Id}", request.Id);
                    return false;
                }

                // 检查状态是否为待处理
                if (application.Status != 0)
                {
                    _logger.LogWarning("退款申请状态不是待处理，无法拒绝，ID：{Id}，当前状态：{Status}", request.Id, application.Status);
                    return false;
                }

                // 更新退款申请状态
                application.Status = 2; // 已拒绝
                application.ProcessTime = DateTime.Now;
                application.ProcessorId = request.OperatorId;
                application.Remark = request.Remark;
                application.UpdatedAt = DateTime.Now;

                // 创建退款日志
                var refundLog = new RefundLog
                {
                    ApplicationId = request.Id,
                    Status = 2, // 已拒绝
                    OperatorId = request.OperatorId,
                    OperateTime = DateTime.Now,
                    Remark = request.Remark ?? "拒绝退款",
                    CreatedAt = DateTime.Now
                };

                // 保存到数据库
                _context.RefundLog.Add(refundLog);
                await _context.SaveChangesAsync();

                _logger.LogInformation("退款申请拒绝成功，ID：{Id}", request.Id);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "拒绝退款申请失败，ID：{Id}", request.Id);
                return false;
            }
        }

        /// <summary>
        /// 清除缓存
        /// </summary>


        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">筛选请求</param>
        /// <returns>筛选后的查询</returns>
        private static IQueryable<RefundApplication> ApplyFilters(IQueryable<RefundApplication> query, RefundApplicationQueryRequest request)
        {
            // 患者信息筛选（手机号）
            if (!string.IsNullOrWhiteSpace(request.PatientInfo))
            {
                // 根据申请编号进行筛选
                query = query.Where(x => x.ApplicationNo != null && x.ApplicationNo.Contains(request.PatientInfo));
            }

            // 申请时间范围筛选
            if (request.ApplyStartTime.HasValue)
            {
                query = query.Where(x => x.ApplyTime >= request.ApplyStartTime.Value);
            }

            if (request.ApplyEndTime.HasValue)
            {
                query = query.Where(x => x.ApplyTime <= request.ApplyEndTime.Value);
            }

            // 状态筛选
            if (request.Status.HasValue)
            {
                query = query.Where(x => x.Status == request.Status.Value);
            }

            return query;
        }

        /// <summary>
        /// 获取状态文本
        /// </summary>
        /// <param name="status">状态值</param>
        /// <returns>状态文本</returns>
        private static string GetStatusText(int? status)
        {
            return status switch
            {
                0 => "待处理",
                1 => "已处理",
                2 => "已拒绝",
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取来源文本
        /// </summary>
        /// <param name="refundType">退款类型</param>
        /// <param name="extraInfo">扩展信息</param>
        /// <returns>来源文本</returns>
        private static string GetSourceText(string? refundType, string? extraInfo)
        {
            // 直接返回退款类型作为来源
            if (!string.IsNullOrWhiteSpace(refundType))
            {
                return refundType;
            }

            return "未知来源";
        }

        /// <summary>
        /// 获取用户手机号（需要关联用户表）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>手机号</returns>
        private static string GetUserPhone(long? userId)
        {
            // 这里需要关联用户表获取手机号
            // 暂时返回模拟数据
            if (userId.HasValue)
            {
                // 实际项目中应该查询用户表
                return $"188{userId.Value:D8}";
            }
            return string.Empty;
        }
    }
} 